﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Authorization;
using FwProject.Controllers;
using Microsoft.AspNetCore.Mvc;
using QRCoder;
using FwProject.Restaurant;
using Newtonsoft.Json;
using Abp.AutoMapper;
using System.Net;
using System.Linq;
using FwProject.Restaurant.Dto;

namespace FwProject.Web.Controllers
{
    [AbpMvcAuthorize]
    public class QRCoderController: FwProjectControllerBase
    {
        private readonly IRestaurantAppService _restaurantAppService;
        public QRCoderController(IRestaurantAppService restaurantAppService)
        {
            _restaurantAppService = restaurantAppService;
        }


        /// <summary>
        /// 根据餐厅编号得到生成餐厅数据源数据
        /// </summary>
        /// <returns>The index.</returns>
        /// <param name="id">Identifier.</param>
        public async  Task<ActionResult> Index(Guid id)
        {
            var model= (await _restaurantAppService.GetByIdAsync(id)).MapTo<QrModel>();
            string strCode = $"{JsonConvert.SerializeObject(model)}";
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();

            QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.H);

            QRCode qrcode = new QRCode(qrCodeData);
            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap qrCodeImage = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false);
            MemoryStream ms = new MemoryStream();
            qrCodeImage.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/Jpeg");

            // return Redirect($"https://cli.im/api/qrcode/code?text={WebUtility.UrlEncode(strCode)}");
        }

        /// <summary>
        /// 根据餐厅编号得到生成餐厅数据源数据
        /// </summary>
        /// <returns>The index.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<ActionResult> DownLoadQRCode(Guid id)
        {
            var model = (await _restaurantAppService.GetByIdAsync(id)).MapTo<QrModel>();
            string strCode = $"{JsonConvert.SerializeObject(model)}";
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.H);
            QRCode qrcode = new QRCode(qrCodeData);
            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap qrCodeImage = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false);
            MemoryStream ms = new MemoryStream();
            qrCodeImage.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/Jpeg","qrCodeImage.jpg");
        }
    }


    [AutoMap(typeof(RestaurantDto))]
    public class QrModel {

        public Guid Id { get; set; }
        public string RestaurantName { get; set; }
        public long EmployeeDriverid { get; set; }
    }
}
